#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <string>

void Usage(std::string proc)
{
    std::cout << "Usage# " << proc << " [clientip]+[port]" << std::endl;
}
// ./tcpclient 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 初始化
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    // 主机转网络
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    int sockfd = 0;
    while (true)
    {
        int cnt = 5;
        bool isreconnect = false;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return 1;
        }
        do
        {
            int s = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (s < 0)
            {
                isreconnect = true;
                std::cerr << "connect error...,cnt: " << cnt << std::endl;
                sleep(2);
                cnt--;
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        while (true)
        {

            std::string message;
            std::cout << "Please Enter# " << std::endl;
            std::getline(std::cin, message);

            int n = write(sockfd, message.c_str(), message.size());

            if (n < 0)
            {
                std::cerr << "write error" << std::endl;
                continue;
            }
            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                //  continue;
            }
        }
        close(sockfd);
    }

    return 0;
}
